import img from "./row.png";
import img2 from "./row2.png";
import img3 from "./row3.png";
import img4 from "./row4.png";
import source from "./source.glsl?raw";

export class PolylineTrailLinkMaterialPropertyRoad {
  constructor(options) {
    this._definitionChanged = new Cesium.Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this.color = options.color;
    this.duration = options.duration;
    this.repeatCount = options.repeatCount;
    this._time = new Date().getTime();
    // console.log("es6流动线", this, options);
    // 使用 JulianDate 获取当前时间（秒）
    // const now = Cesium.JulianDate.now();
    // this._startTime = Cesium.JulianDate.toSeconds(now);
  }

  get isConstant() {
    return false;
  }

  get definitionChanged() {
    return this._definitionChanged;
  }

  getType(time) {
    return Cesium.Material.PolylineTrailLinkMaterialType;
  }

  getValue(time, result) {
    if (!Cesium.defined(result)) {
      result = {};
    }
    result.color = Cesium.Property.getValueOrClonedDefault(
      this.color,
      time,
      Cesium.Color.WHITE,
      result.color,
    );
    result.repeatCount = Cesium.Property.getValueOrClonedDefault(
      this.repeatCount,
      time,
      1, //默认值
      result.repeatCount,
    );
    result.time =
      ((new Date().getTime() - this._time) % this.duration) / this.duration;
    return result;
  }

  equals(other) {
    return (
      this === other ||
      (other instanceof PolylineTrailLinkMaterialPropertyRoad &&
        Cesium.Property.equals(this.color, other.color) &&
        Cesium.Property.equals(this.repeatCount, other.repeatCount))
      // Cesium.Property.equals(this._duration, other._duration))
    );
  }
}
registerMaterial();

function registerMaterial() {
  console.log("注册材质", Cesium.Material._materialCache);
  if (
    Cesium.Material._materialCache?.getMaterial(
      Cesium.Material.PolylineTrailLinkMaterialType,
    )
  ) {
    return; // 避免重复注册
  }
  Object.defineProperties(PolylineTrailLinkMaterialPropertyRoad.prototype, {
    color: Cesium.createPropertyDescriptor("color"),
    duration: Cesium.createPropertyDescriptor("duration"),
    repeatCount: Cesium.createPropertyDescriptor("repeatCount"),
    time: Cesium.createPropertyDescriptor("time"),
  });

  Cesium.PolylineTrailLinkMaterialPropertyRoad =
    PolylineTrailLinkMaterialPropertyRoad;
  Cesium.Material.PolylineTrailLinkMaterialType =
    "PolylineTrailLinkMaterialType";

  Cesium.Material._materialCache.addMaterial(
    Cesium.Material.PolylineTrailLinkMaterialType,
    {
      fabric: {
        type: Cesium.Material.PolylineTrailLinkMaterialType,
        uniforms: {
          color: new Cesium.Color(1.0, 0.0, 0.0, 1), //修改渲染颜色
          image: img4, //修改传入图片
          time: 0,
          repeatCount: 0, // 控制图片重复长度
          depthFailMaterial: true,
        },
        source: source,
      },
      translucent: function (material) {
        return true;
      },
    },
  );
}
